<?php
require_once 'config.php';

// 检查用户是否已登录
if (!isLoggedIn()) {
    $_SESSION['flash_message'] = "请先登录后再进行借阅";
    $_SESSION['flash_type'] = "warning";
    redirect('login.php');
}

// 获取图书ID
$book_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($book_id <= 0) {
    $_SESSION['flash_message'] = "无效的图书ID";
    $_SESSION['flash_type'] = "danger";
    redirect('books.php');
}

try {
    // 开始事务
    $pdo->beginTransaction();
    
    // 获取图书信息
    $stmt = $pdo->prepare("SELECT * FROM books WHERE book_id = ? FOR UPDATE");
    $stmt->execute([$book_id]);
    $book = $stmt->fetch();
    
    if (!$book) {
        $pdo->rollBack();
        $_SESSION['flash_message'] = "未找到该图书";
        $_SESSION['flash_type'] = "danger";
        redirect('books.php');
    }
    
    // 检查图书是否可借
    if ($book['available'] <= 0) {
        $pdo->rollBack();
        $_SESSION['flash_message'] = "该图书已全部借出，暂时无法借阅";
        $_SESSION['flash_type'] = "warning";
        redirect('book_detail.php?id=' . $book_id);
    }
    
    // 检查用户是否已借阅该图书
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM borrowings WHERE user_id = ? AND book_id = ? AND status = 'borrowed'");
    $stmt->execute([$_SESSION['user_id'], $book_id]);
    if ($stmt->fetchColumn() > 0) {
        $pdo->rollBack();
        $_SESSION['flash_message'] = "您已借阅过该图书，请勿重复借阅";
        $_SESSION['flash_type'] = "warning";
        redirect('my_borrowings.php');
    }
    
    // 设置借阅日期和归还日期
    $borrow_date = date('Y-m-d H:i:s');
    $return_date = date('Y-m-d', strtotime('+30 days')); // 借阅期限为30天
    
    // 插入借阅记录
    $stmt = $pdo->prepare("INSERT INTO borrowings (user_id, book_id, borrow_date, return_date, status) VALUES (?, ?, ?, ?, 'borrowed')");
    $stmt->execute([$_SESSION['user_id'], $book_id, $borrow_date, $return_date]);
    
    // 更新图书可借数量
    $stmt = $pdo->prepare("UPDATE books SET available = available - 1 WHERE book_id = ?");
    $stmt->execute([$book_id]);
    
    // 提交事务
    $pdo->commit();
    
    // 设置成功消息
    $_SESSION['flash_message'] = "借阅成功！请在 {$return_date} 前归还图书";
    $_SESSION['flash_type'] = "success";
    
    // 重定向到我的借阅页面
    redirect('my_borrowings.php');
    
} catch(PDOException $e) {
    // 回滚事务
    $pdo->rollBack();
    
    $_SESSION['flash_message'] = "借阅失败: " . $e->getMessage();
    $_SESSION['flash_type'] = "danger";
    redirect('book_detail.php?id=' . $book_id);
}
?> 